<template>
  <div class="swipe-container">
    <!-- 主要内容 -->
    <div class="content" @touchstart="handleTouchStart" @touchmove="handleTouchMove" @touchend="handleTouchEnd" :style="{ transform: `translateX(${translateX}px)` }">
      <slot name="content"></slot>
    </div>
    <!-- 删除按钮 -->
    <div class="action-buttons" :style="{ transform: `translateX(${actionTranslateX}px)` }">
      <slot name="actions"></slot>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref } from "vue";

// 定义滑动相关变量
const startX = ref(0);
const translateX = ref(0); // 主体内容的位移
const actionTranslateXO = 60;
const actionTranslateX = ref(actionTranslateXO); // 删除按钮的位移（初始隐藏）
const maxSwipeDistance = 100; // 滑动的最大距离（px）


// 触摸开始事件
const handleTouchStart = (event: TouchEvent) => {
  startX.value = event.touches[0].clientX;
  translateX.value = 0; // 重置滑动距离
  actionTranslateX.value = actionTranslateXO; // 重置删除按钮位置
};

// 触摸移动事件
const handleTouchMove = (event: TouchEvent) => {
  const currentX = event.touches[0].clientX;
  const diff = startX.value - currentX;

  // 限制滑动范围
  if (diff >= 0 && diff <= maxSwipeDistance) {
    translateX.value = -diff; // 主体内容向左移动
    actionTranslateX.value = maxSwipeDistance - diff; // 删除按钮向右显示
  }
};

// 触摸结束事件
const handleTouchEnd = () => {
  if (Math.abs(translateX.value) > maxSwipeDistance / 2) {
    // 如果滑动超过一半，则保持打开状态
    translateX.value = -actionTranslateXO;
    actionTranslateX.value = 0;
  } else {
    // 否则恢复原始状态
    translateX.value = 0;
    actionTranslateX.value = actionTranslateXO;
  }
};

</script>

<style scoped>
.swipe-container {
  display: flex;
  position: relative;
  overflow: hidden;
  width: 100%;
}

.content {
  flex: 1;
  transition: transform 0.3s ease;
  position: relative;
}

.action-buttons {
  position: absolute;
  top: 0;
  bottom: 0;
  right: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #ff4d4f;
  color: white;
  width: 60px;
  transition: transform 0.3s ease;
}
</style>